﻿using System;
using System.Collections.Generic;
using System.Web;
using ChuanYe.Models;
using ChuanYe.IBLL;
using ChuanYe.Commom;
using Microsoft.Practices.Unity;
using ChuanYe.Models.Model;
using ChuanYe.DAL;
using System.Web.Http.Cors;
using ChuanYe.Utils;
using System.Linq;

namespace SJPlatForm.Web.Controllers
{
    [EnableCors("*", "*", "*")]
    public class UsersInfoController : BaseApiController
    {
        [Dependency]
        public IUsersInfosBLL s_DAL { get; set; }


        [Dependency]
        public ISafetyInfoBLL f_bll { get; set; }

        [Dependency]
        public ISms_SendInfoBLL m_bll { get; set; }




        #region 模块管理
        ///// <summary>
        ///// 添加模块
        ///// </summary>
        ///// <param name="obj"></param>
        ///// <returns></returns>
        //public int PowerCreate(dynamic obj)
        //{
        //    Power model = new Power();
        //    return s_DAL.PowerCreate(model);
        //}
        ///// <summary>
        ///// 删除模块
        ///// </summary>
        ///// <param name="ID">模块ID</param>
        ///// <returns></returns>
        //public int PowerDelete(int ID)
        //{
        //    return s_DAL.PowerDelete(ID);
        //}
        ///// <summary>
        ///// 模块详情
        ///// </summary>
        ///// <param name="ID">模块ID</param>
        ///// <returns></returns>
        //public Power PowerInfo(int ID)
        //{
        //    return s_DAL.PowerInfo(ID);
        //}
        ///// <summary>
        ///// 修改模块
        ///// </summary>
        ///// <param name="model"></param>
        ///// <returns></returns>
        //public int PowerUpdate(Power model)
        //{
        //    return s_DAL.PowerUpdate(model);
        //}
        ///// <summary>
        ///// 查询模块
        ///// </summary>
        ///// <param name="model"></param>
        ///// <returns></returns>
        //public PowerResult PowerGetList(PowerSearch Search, GridPager Pager)
        //{
        //    return s_DAL.PowerGetList(Search, Pager);
        //}
        ///// <summary>
        ///// 查询全部模块
        ///// </summary>
        ///// <param name="model"></param>
        ///// <returns></returns>
        //public List<Power> PowerGetAll(PowerSearch Search, GridPager Pager)
        //{
        //    return s_DAL.PowerGetAll(Search, Pager);
        //}
        #endregion

        #region 职务管理
        /// <summary>
        /// 是否已有相同的职务名称
        /// </summary>
        /// <param name="obj">职务名称：PositionName</param>
        /// <returns></returns>
        public int PositionIsHave(dynamic obj)
        {
            try
            {
                string PositionName = obj.PositionName;
                int result = s_DAL.PositionIsHave(PositionName);
                return result;
            }
            catch (Exception ex)
            {
                Log.Error("UsersInfoController", ex.ToString());
                return -1;
            }
        }
        /// <summary>
        /// 添加职务
        /// </summary>
        /// <param name="obj">职务名称：PositionName，排序：Sort</param>
        /// <returns></returns>
        public int PositionCreate(dynamic obj)
        {
            try
            {
                string PositionName = obj.PositionName;
                int count = s_DAL.PositionIsHave(PositionName);
                if (count > 0)
                {
                    return -2;
                }
                Position model = new Position();
                model.PositionName = obj.PositionName;
                model.Sort = obj.Sort;
                int result= s_DAL.PositionCreate(model);
                if (result > 0)
                {
                    Log.Info(obj.key.ToString(), "职务管理", "职务添加成功！");
                }
                return result;
            }
            catch (Exception ex) {
                Log.Error("UsersInfoController", ex.ToString());
                return -1;
            }
        }
        /// <summary>
        /// 删除职务
        /// </summary>
        /// <param name="obj">职务ID：ID</param>
        /// <returns></returns>
        public int PositionDelete(dynamic obj)
        {
            try
            {
                int ID = Convert.ToInt32(obj.ID);
                int result= s_DAL.PositionDelete(ID);
                if (result > 0)
                {
                    Log.Info(obj.key.ToString(), "职务管理", "职务删除成功！");
                }
                return result;
            }
            catch (Exception ex) {
                Log.Error("UsersInfoController", ex.ToString());
                return -1;
            }
        }
        /// <summary>
        /// 职务详情
        /// </summary>
        /// <param name="obj">职务ID：ID</param>
        /// <returns></returns>
        public Position PositionInfo(dynamic obj)
        {
            try
            {
                int ID = Convert.ToInt32(obj.ID);
                return s_DAL.PositionInfo(ID);
            }
            catch (Exception ex)
            {
                Log.Error("UsersInfoController", ex.ToString());
                return new Position();
            }
        }
        /// <summary>
        /// 修改职务
        /// </summary>
        /// <param name="obj">职务名称：PositionName，排序：Sort,职务ID：ID</param>
        /// <returns></returns>
        public int PositionUpdate(dynamic obj)
        {
            try
            {
                Position model = new Position();
                model.PositionName = obj.PositionName;
                model.Sort = obj.Sort;
                model.ID = obj.ID;

                int count = s_DAL.PositionIsHave(model.PositionName,model.ID);
                if(count > 0)
                {
                    return -2;
                }
                int result = s_DAL.PositionUpdate(model);
                if (result >-1)
                {
                    Log.Info(obj.key.ToString(), "职务管理", "职务修改成功！");
                }
                return result;
            }
            catch (Exception ex)
            {
                Log.Error("UsersInfoController", ex.ToString());
                return -1;
            }
        }
        /// <summary>
        /// 获取全部职务
        /// </summary>
        /// <returns></returns>
        public List<Position> PositionGetAll()
        {
            try {
                return s_DAL.PositionGetAll();
            }
            catch (Exception ex)
            {
                Log.Error("UsersInfoController", ex.ToString());
                return new List<Position>();
            }
        }

        /// <summary>
        /// 获取职务 分页
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public dynamic PositionByPage(dynamic obj)
        {
            try
            {
                OutsideUserInfoSearch Search = new OutsideUserInfoSearch();
                string positionName = obj.Keyword;
                GridPager pager = new GridPager();
                pager.page = obj.page == null ? 1 : Convert.ToInt32(obj.page);
                pager.rows = obj.rows == null ? 10 : Convert.ToInt32(obj.rows);
               
                var data = s_DAL.PositionByPage(positionName,pager);
                return new { PositionList = data, TotalRows = pager.totalRows };
            }
            catch (Exception ex)
            {
                Log.Error("UsersInfoController", ex.ToString());
                return null;
            }
        }

        
        #endregion

        #region 角色管理
        /// <summary>
        /// 获取权限树
        /// </summary>
        /// <returns></returns>
        public List<PowerModel> PowerGetAllTree()
        {
            return s_DAL.PowerGetAllTree();
        }
        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="obj">角色描述：Description,是否启用：Enabled,角色名称：RoleName,,模块ID：IDS 格式：ID,ID,ID</param>
        /// <returns></returns>
        public int RolesCreate(dynamic obj)
        {
            try
            {
                MemberShip_Roles model = new MemberShip_Roles();
                model.Description = obj.Description;
                model.Enabled = obj.Enabled == 0 ? false : true;
                model.RoleName = obj.RoleName;

                RolePower RP = new RolePower();
                RP.RP_TransDatetime = DateTime.Now;
                RP.RP_TransUser = GetLoginInfo(obj.key.ToString()).UserName;
                #region 获取客户端IP
                string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (string.IsNullOrEmpty(result))
                {
                    result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                }
                if (string.IsNullOrEmpty(result))
                {
                    result = HttpContext.Current.Request.UserHostAddress;
                }
                if (string.IsNullOrEmpty(result))
                {
                    result = "0.0.0.0";
                }
                RP.RP_TransIP = result;
                #endregion
                List<RolePower> RolePowerList = new List<RolePower>();
                string IDS = obj.IDS;
                string[] IDList = IDS.Split(',');
                for (int i = 0; i < IDList.Length; i++)
                {
                    RolePower RPAdd = new RolePower();
                    RPAdd.RP_TransDatetime = RP.RP_TransDatetime;
                    RPAdd.RP_TransIP = RP.RP_TransIP;
                    RPAdd.RP_TransUser = RP.RP_TransUser;
                    RPAdd.P_ID= IDList[i];
                    RolePowerList.Add(RPAdd);
                }
                int RT= s_DAL.RolesCreate(model, RolePowerList);
                if (RT > 0)
                {
                    Log.Info(obj.key.ToString(), "角色管理", "角色添加成功！");
                }
                return RT;
            }
            catch (Exception ex)
            {
                Log.Error("UsersInfoController", ex.ToString());
                return -1;
            }
        }
        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="obj">角色ID：ID</param>
        /// <returns></returns>
        public int RolesDelete(dynamic obj)
        {
            try
            {
                int ID = Convert.ToInt32(obj.ID);
                int RT = s_DAL.RolesDelete(ID);
                if (RT > 0)
                {
                    Log.Info(obj.key.ToString(), "角色管理", "角色删除成功！");
                }
                return RT;
            }
            catch (Exception ex)
            {
                Log.Error("UsersInfoController", ex.ToString());
                return -1;
            }
        }
        /// <summary>
        /// 角色详情
        /// </summary>
        /// <param name="obj">角色ID：ID</param>
        /// <returns></returns>
        public dynamic RolesInfo(dynamic obj)
        {
            try
            {
                int ID = Convert.ToInt32(obj.ID);
                //MemberShip_RolesResult dsd= s_DAL.RolesInfo(ID);
                var list = s_DAL.RolesInfo(ID);
                int roleType = 0;
                if (list.RolePowerList != null)
                {
                    var  roleCityEntity=list.RolePowerList.Where(p => p.P_ID == "SJ100000").FirstOrDefault();
                    var  roleCountyEntity = list.RolePowerList.Where(p => p.P_ID == "QX100000").FirstOrDefault();
                    if (roleCityEntity != null)
                    {
                        roleType = 1;
                    }else if (roleCountyEntity != null)
                    {
                        roleType = 2;
                    }
                }
                return new {RoleType=roleType,List= list };
            }
            catch (Exception ex)
            {
                Log.Error("UsersInfoController", ex.ToString());
                return  new { RoleType = 0, List = new MemberShip_RolesResult() } ;
            }
        }
        /// <summary>
        /// 修改角色
        /// </summary>
        /// <param name="obj">角色ID:ID,角色描述：Description,是否启用：Enabled,上级ID：FID,角色名称：RoleName,模块ID：IDS 格式：ID,ID,ID</param>
        /// <returns></returns>
        public int RolesUpdate(dynamic obj)
        {
            try
            {
                MemberShip_Roles model = new MemberShip_Roles();
                model.ID = obj.ID;
                model.Description = obj.Description;
                model.Enabled = obj.Enabled == 0 ? false : true;
                model.RoleName = obj.RoleName;

                RolePower RP = new RolePower();
                RP.RP_TransDatetime = DateTime.Now;
                RP.RP_TransUser = GetLoginInfo(obj.key.ToString()).UserName;
                #region 获取客户端IP
                string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (string.IsNullOrEmpty(result))
                {
                    result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                }
                if (string.IsNullOrEmpty(result))
                {
                    result = HttpContext.Current.Request.UserHostAddress;
                }
                if (string.IsNullOrEmpty(result))
                {
                    result = "0.0.0.0";
                }
                RP.RP_TransIP = result;
                #endregion
                List<RolePower> RolePowerList = new List<RolePower>();
                string IDS = obj.IDS;
                string[] IDList = IDS.Split(',');
                for (int i = 0; i < IDList.Length; i++)
                {
                    RolePower RPAdd = new RolePower();
                    RPAdd.RP_TransDatetime = RP.RP_TransDatetime;
                    RPAdd.RP_TransIP = RP.RP_TransIP;
                    RPAdd.RP_TransUser = RP.RP_TransUser;
                    RPAdd.R_ID = obj.ID;
                    RPAdd.P_ID = IDList[i];
                    RolePowerList.Add(RPAdd);
                }
                int RT = s_DAL.RolesUpdate(model, RolePowerList);
                if (RT > 0)
                {
                    Log.Info(obj.key.ToString(), "角色管理", "角色修改成功！");
                }
                return RT;
            }
            catch (Exception ex)
            {
                Log.Error("UsersInfoController", ex.ToString());
                return -1;
            }
        }
        /// <summary>
        /// 获取全部角色
        /// </summary>
        /// <returns></returns>
        public List<MemberShip_Roles> MemberShip_RolesGetAll()
        {
            try
            {
                return s_DAL.MemberShip_RolesGetAll();
            }
            catch (Exception ex)
            {
                Log.Error("UsersInfoController", ex.ToString());
                return new List<MemberShip_Roles>();
            }
        }
        /// <summary>
        /// 分页查询角色
        /// </summary>
        /// <param name="obj">页数：page,行数：rows</param>
        /// <returns></returns>
        public MemberShip_RolesSearchResult MemberShip_RolesSearch(dynamic obj)
        {
            try
            {
                GridPager Pager = new GridPager();
                Pager.page = obj.page == null ? 1 : Convert.ToInt32(obj.page);
                Pager.rows = obj.rows == null ? 10 : Convert.ToInt32(obj.rows);
                return s_DAL.MemberShip_RolesSearch(Pager);
            }
            catch (Exception ex)
            {
                Log.Error("UsersInfoController", ex.ToString());
                return new MemberShip_RolesSearchResult();
            }
        }
        #endregion

        #region 机构管理
        /// <summary>
        /// 添加机构
        /// </summary>
        /// <param name="obj">机构名称：DepName，负责人账号：ManagerCode，负责人：Manager，部门电话：DepTel，部门领导：Leader，领导电话：LeaderTel，是否平安报送：IsSend，显示顺序：Sort，所在地：Address，上级机构：FID</param>
        /// <returns></returns>
        public int DepartmentsCreate(dynamic obj)
        {
            try
            {
                Departments model = new Departments();
                model.Address = obj.Address;
                model.DepName = obj.DepName;
                model.DepTel = obj.DepTel;
                model.FID = obj.FID;
                model.IsSend = obj.IsSend==1?true:false;
                model.Leader = obj.Leader;
                model.LeaderTel = obj.LeaderTel;
                model.Manager = obj.Manager;
                model.ManagerCode = obj.ManagerCode;
                model.Sort = obj.Sort;
                int RT= s_DAL.DepartmentsCreate(model);
                if (RT > 0)
                {
                    Log.Info(obj.key.ToString(), "机构管理", "机构添加成功！");
                }
                return RT;
            }
            catch (Exception ex) {
                Log.Error("UsersInfoController", ex.ToString());
                return -1;
            }
        }
        /// <summary>
        /// 删除机构
        /// </summary>
        /// <param name="obj">机构ID：ID</param>
        /// <returns></returns>
        public int DepartmentsDelete(dynamic obj)
        {
            try
            {
                int ID = Convert.ToInt32(obj.ID);
                int RT= s_DAL.DepartmentsDelete(ID);
                if (RT > 0)
                {
                    Log.Info(obj.key.ToString(), "机构管理", "机构删除成功！");
                }
                return RT;
            }
            catch (Exception ex) {
                Log.Error("UsersInfoController", ex.ToString());
                return -1;
            }
        }
        /// <summary>
        /// 机构详情
        /// </summary>
        /// <param name="obj">机构ID：ID</param>
        /// <returns></returns>
        public Departments DepartmentsInfo(dynamic obj)
        {
            try
            {
                int ID = Convert.ToInt32(obj.ID);
                return s_DAL.DepartmentsInfo(ID);
            }
            catch (Exception ex)
            {
                Log.Error("UsersInfoController", ex.ToString());
                return new Departments();
            }
        }
        /// <summary>
        /// 修改机构
        /// </summary>
        /// <param name="obj">机构ID:ID,机构名称：DepName，负责人账号：ManagerCode，负责人：Manager，部门电话：DepTel，部门领导：Leader，领导电话：LeaderTel，是否平安报送：IsSend，显示顺序：Sort，所在地：Address，上级机构：FID</param>
        /// <returns></returns>
        public int DepartmentsUpdate(dynamic obj)
        {
            try
            {
                Departments model = new Departments();
                model.ID = obj.ID;
                model.Address = obj.Address;
                model.DepName = obj.DepName;
                model.DepTel = obj.DepTel;
                model.FID = obj.FID;
                model.IsSend = obj.IsSend == 1 ? true : false;
                model.Leader = obj.Leader;
                model.LeaderTel = obj.LeaderTel;
                model.Manager = obj.Manager;
                model.ManagerCode = obj.ManagerCode;
                model.Sort = obj.Sort;
                int RT = s_DAL.DepartmentsUpdate(model);
                if (RT > -1)
                {
                    Log.Info(obj.key.ToString(), "机构管理", "机构修改成功！");
                }
                return RT;
            }
            catch (Exception ex)
            {
                Log.Error("UsersInfoController", ex.ToString());
                return -1;
            }
        }
        /// <summary>
        /// 机构查询
        /// </summary>
        /// <param name="obj">页数：page，行数：rows</param>
        /// <returns></returns>
        public DepartmentsSearchResult DepartmentsSearch(dynamic obj)
        {
            try
            {
                DepartmentsSearch Search = new ChuanYe.Models.DepartmentsSearch();
                GridPager Pager = new GridPager();
                Pager.page = obj.page == null ? 1 : Convert.ToInt32(obj.page);
                Pager.rows = obj.rows == null ? 10 : Convert.ToInt32(obj.rows);
                return s_DAL.DepartmentsSearch(Search, Pager);
            }
            catch (Exception ex)
            {
                Log.Error("UsersInfoController", ex.ToString());
                return new DepartmentsSearchResult();
            }
        }
        /// <summary>
        /// 获取部门下拉框数据
        /// </summary>
        /// <returns></returns>
        public List<DepartmentsAllModel> DepartmentsGetAll()
        {
            try
            {
                return s_DAL.DepartmentsGetAll();
            }
            catch (Exception ex)
            {
                Log.Error("UsersInfoController", ex.ToString());
                return new List<DepartmentsAllModel>();
            }
        }
        #endregion

        #region 用户管理
        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="obj">用户账号：UserCode，用户姓名：UserName，部门ID：Section，密码：PassWord，角色ID：RoleID，电话：Phone，职务ID：PositionID，排序：Sort，是否公共邮箱：Division,是否接收平安报送：IsSafeDelivery,是否为管理员账号：IsManager</param>
        /// <returns></returns>
        public int UsersInfosCreate(dynamic obj)
        {
            try
            {
                if (string.IsNullOrEmpty(obj.PassWord.ToString()))
                {
                    return -4;
                }
                UsersInfos model = new UsersInfos();
                model.UserCode = obj.UserCode;
                model.UserName = obj.UserName;
                model.Section = obj.Section;
                model.PassWord = SundryHelper.MD5(obj.PassWord.ToString());
                model.RoleID = obj.RoleID;
                model.Phone = obj.Phone;
                model.PositionID = obj.PositionID;
                model.Sort = obj.Sort;
                model.CreateTime = DateTime.Now;

                model.Division = obj.Division;
                model.IsSafeDelivery = obj.IsSafeDelivery == 1 ? true : false;
                model.IsManager= obj.IsManager == 1 ? true : false;
                model.IsOfficial= obj.IsOfficial == 1 ? true : false;
                model.IsFire = obj.IsFire == 1 ? true : false;


                //判定公文短信在每个部门下最多只有3个
                if (model.IsOfficial != null && model.IsOfficial == true)
                {
                    int count=s_DAL.UsersInfosCount(model.PositionID.Value, model.IsOfficial.Value);
                    if (count >= 3)
                    {
                        return -5;
                    }
                }

                var exist = s_DAL.UsersInfosByUserCode(model.UserCode);

                if (string.IsNullOrEmpty(model.UserCode) || string.IsNullOrEmpty(model.PassWord) || string.IsNullOrEmpty(model.UserName))
                {
                    return -3;
                }
                else if (exist != null && exist.Count>0)
                {
                    return -2;
                } 
                else
                {
                    int RT = s_DAL.UsersInfosCreate(model);
                    if (RT > -1)
                    {
                        Log.Info(obj.key.ToString(), "用户管理", "用户添加成功！");
                    }
                    return RT;
                }
            }
            catch (Exception ex)
            {
                Log.Error("UsersInfoController", ex.ToString());
                return -1;
            }
        }
        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="obj">用户ID：ID</param>
        /// <returns></returns>
        public int UsersInfosDelete(dynamic obj)
        {
            try
            {
                int ID = Convert.ToInt32(obj.ID);
                int RT = s_DAL.UsersInfosDelete(ID);
                if (RT > 0)
                {
                    Log.Info(obj.key.ToString(), "用户管理", "用户删除成功！");
                }
                return RT;
            }
            catch (Exception ex)
            {
                Log.Error("UsersInfoController", ex.ToString());
                return -1;
            }
        }
        /// <summary>
        /// 用户详情
        /// </summary>
        /// <param name="obj">用户ID：ID</param>
        /// <returns></returns>
        public UsersInfos UsersInfosInfo(dynamic obj)
        {
            try
            {
                int ID = Convert.ToInt32(obj.ID);
                return s_DAL.UsersInfosInfo(ID);
            }
            catch (Exception ex)
            {
                Log.Error("UsersInfoController", ex.ToString());
                return new UsersInfos();
            }
        }


        /// <summary>
        /// 用户修改
        /// </summary>
        /// <param name="obj">用户ID：ID，用户账号：UserCode，用户姓名：UserName，部门ID：Section，密码：PassWord，角色ID：RoleID，电话：Phone，职务ID：PositionID，排序：Sort，是否公共邮箱：Division,是否接收平安报送：IsSafeDelivery,是否为管理员账号：IsManager</param>
        /// <returns></returns>
        public int UsersInfosUpdate(dynamic obj)
        {
            try
            {
                UsersInfos model = new UsersInfos();
                model.ID = obj.ID;
                model.UserCode = obj.UserCode;
                model.UserName = obj.UserName;
                model.Section = obj.Section;
                model.PassWord = obj.PassWord==null?null:SundryHelper.MD5(obj.PassWord.ToString());
                model.RoleID = obj.RoleID;
                model.Phone = obj.Phone;
                model.PositionID = obj.PositionID;
                model.Sort = obj.Sort;
                model.CreateTime = DateTime.Now;

                model.Division = obj.Division;
                model.IsSafeDelivery = obj.IsSafeDelivery == 1 ? true : false;
                model.IsManager = obj.IsManager == 1 ? true : false;
                model.IsOfficial = obj.IsOfficial == 1 ? true : false;
                model.IsFire = obj.IsFire == 1 ? true : false;

                var exist = s_DAL.UsersInfosByUserCode(model.UserCode);

                if (string.IsNullOrEmpty(model.UserCode) ||  string.IsNullOrEmpty(model.UserName))
                {
                    return -3;
                }
                else if (exist != null && exist.Where(p => p.ID != model.ID).FirstOrDefault() != null)
                {
                    return -2;
                }
                else
                {
                    int RT = s_DAL.UsersInfosUpdate(model);
                    if (RT > -1)
                    {
                        Log.Info(obj.key.ToString(), "用户管理", "用户修改成功！");
                    }
                    return RT;
                }
            }
            catch (Exception ex)
            {
                Log.Error("UsersInfoController", ex.ToString());
                return -1;
            }
        }

        /// <summary>
        /// 修改禁用状态 1.禁用  0 可用
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public int  UsersInfosUpdateDisable(dynamic obj)
        {
            try
            {
                int userid = obj.ID;
                bool? disable = obj.IsDisable;
                var model=s_DAL.UsersInfosInfo(userid);
                if (model == null)
                {
                    return -1;
                }
                bool isDisable = disable == null ? false : disable.Value;

                if (isDisable == true)
                {
                    //调整禁用后的在线值守
                    model.IsManager = false;
                    model.Sort = 0;
                    s_DAL.UsersInfosUpdate(model);
                }
                int RT = s_DAL.UsersInfosUpdateDisable(userid, isDisable);
                if (RT > 0)
                {
                    Log.Info(obj.key.ToString(), "用户管理", "禁用状态修改成功！");
                }
                return RT;
            }
            catch (Exception ex)
            {
                Log.Error("UsersInfoController", ex.ToString());
                return -1;
            }
        }

        /// <summary>
        /// 用户查询
        /// </summary>
        /// <param name="obj">用户姓名：UserName，角色ID：RoleID，部门ID：Section，页数：page，行数：rows</param>
        /// <returns></returns>
        public UsersInfosSearchResult UsersInfosSelete(dynamic obj)
        {
            try
            {
                UsersInfosSearch Search = new UsersInfosSearch();
                Search.UserName = obj.UserName;
                Search.RoleID = obj.RoleID;
                Search.Section = obj.Section;
                GridPager Pager = new GridPager();
                Pager.page = obj.page == null ? 1 : Convert.ToInt32(obj.page);
                Pager.rows = obj.rows == null ? 10 : Convert.ToInt32(obj.rows);
                return s_DAL.UsersInfosSelete2(Search, Pager); //update old method  for UsersInfosSelete
            }
            catch (Exception ex)
            {
                Log.Error("UsersInfoController", ex.ToString());
                return new UsersInfosSearchResult();
            }
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="obj">用户ID：ID</param>
        /// <returns></returns>
        public int ResetPW(dynamic obj)
        {
            try
            {
                UsersInfos model = new UsersInfos();
                model.ID = obj.ID;
                model.PassWord = SundryHelper.MD5("1234");  
                int RT= s_DAL.ChangePW(model);
                if (RT > 0)
                {
                    Log.Info(obj.key.ToString(), "用户管理", "密码重置成功！");
                }
                return RT;
            }
            catch (Exception ex)
            {
                Log.Error("UsersInfoController", ex.ToString());
                return -1;
            }
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="obj">原密码：OldPassWord，新密码：PassWord</param>
        /// <returns></returns>
        public int ChangePW(dynamic obj)
        {
            try
            {
                string oldPassWord = SundryHelper.MD5(obj.OldPassWord.ToString());
                string oldServerPassWord = GetLoginInfo(obj.key.ToString()).PassWord;
                if (oldPassWord.ToLower() != oldServerPassWord.ToLower())
                {
                    return -2;
                }
                UsersInfos model = new UsersInfos();
                model.ID = GetLoginInfo(obj.key.ToString()).ID;
                model.PassWord = SundryHelper.MD5(obj.PassWord.ToString());
                s_DAL.ChangePW(model);
                Log.Info(obj.key.ToString(), "修改密码", "密码修改成功！");
                return 1;
            }
            catch (Exception ex)
            {
                Log.Error("UsersInfoController", ex.ToString());
                return -1;
            }
        }
        #endregion

        #region 操作日志
        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="obj">ID：用户ID，模块名称：ModuleName，描述：Description</param>
        /// <returns></returns>
        public int WriteLog(dynamic obj)
        {
            try
            {
                UsersInfosDAL DAL = new UsersInfosDAL();
                DocOperationLog model = new DocOperationLog();
                LoginUserModel User = s_DAL.LoginUserInfos(Convert.ToInt32(obj.ID));
                model.AccountCode = User.UserCode;
                model.UserName = User.UserName;
                model.ModuleName = obj.ModuleName;//模块名称
                model.Description = obj.Description;//描述
                model.indate = DateTime.Now;
                model.UserID = User.ID;
                #region 获取客户端IP
                string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (string.IsNullOrEmpty(result))
                {
                    result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                }
                if (string.IsNullOrEmpty(result))
                {
                    result = HttpContext.Current.Request.UserHostAddress;
                }
                if (string.IsNullOrEmpty(result))
                {
                    result = "0.0.0.0";
                }
                model.ClientIP = result;
                #endregion

                return  DAL.DocOperationLogCreate(model);
            }
            catch (Exception ex)
            {
                Log.Error("UsersInfoController", ex.ToString());
                return -1;
            }
        }
        /// <summary>
        /// 日志查询
        /// </summary>
        /// <param name="obj">开始时间：stateTime，结束时间：endTime，页数：page，行数：rows</param>
        /// <returns></returns>
        public DocOperationLogResult DocOperationLogSearch(dynamic obj)
        {
            try
            {
                DocOperationLogSearch Search = new ChuanYe.Models.DocOperationLogSearch();
                Search.stateTime = obj.stateTime == "" ? new DateTime() : ValueConvert.StateTimeConvert(obj.stateTime);
                Search.endTime = obj.endTime == "" ? DateTime.Now : ValueConvert.EndTimeConvert(obj.endTime);
                GridPager Pager = new GridPager();
                Pager.page = obj.page == null ? 1 : Convert.ToInt32(obj.page);
                Pager.rows = obj.rows == null ? 10 : Convert.ToInt32(obj.rows);
                return s_DAL.DocOperationLogSearch(Search, Pager);
            }
            catch (Exception ex)
            {
                Log.Error("UsersInfoController", ex.ToString());
                return new DocOperationLogResult();
            }
        }
        #endregion

        #region 短信用户组管理

        /// <summary>
        ///  写入短信组用户信息（外部用户）
        /// </summary>
        /// <returns></returns>
        public int OutsideUserInfoCreate(dynamic obj)
        {
            try
            {

                U_OutsideUserInfos model = new U_OutsideUserInfos();
                model.CreateTime = DateTime.Now;
                model.IsDisable = model.IsDisable;
                model.UserName = obj.UserName;
                model.UserPhone = obj.UserPhone;
                model.IsFireSMS = obj.IsFireSMS;
                model.IsSafeSMS = obj.IsSafeSMS;
                model.IsResponSMS = obj.IsResponSMS ;
                model.PositionID = obj.PositionID;
                model.PositionName = obj.PositionName;
                model.DepName = obj.DepName;
                model.Sort = obj.Sort;
                int RT = s_DAL.AddOutsideUserInfos(model);
                if (RT > 0)
                {
                    Log.Info(obj.key.ToString(), "用户管理", "短信组用户添加成功！");
                }
                return RT;
            }
            catch (Exception ex)
            {
                Log.Error("UsersInfoController", ex.ToString());
                return -1;
            }
        }


        /// <summary>
        /// 查询短信组用户信息
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public dynamic OutsideUserInfoSelect(dynamic obj)
        {
            try
            {
                OutsideUserInfoSearch Search = new OutsideUserInfoSearch();
                Search.UserName = obj.UserName;
                Search.UserPhone = obj.UserPhone;
                GridPager Pager = new GridPager();
                Pager.page = obj.page == null ? 1 : Convert.ToInt32(obj.page);
                Pager.rows = obj.rows == null ? 10 : Convert.ToInt32(obj.rows);
                int totalRows = 0;
                var data= s_DAL.OutsideUserInfosSelect(Search,Pager,ref totalRows);
                return new { OutsideUserInfoList = data, TotalRows = totalRows };
            }
            catch (Exception ex)
            {
                Log.Error("UsersInfoController", ex.ToString());
                return null;
            }
        }

        /// <summary>
        /// 移除短信组用户信息
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public int OutsideUserInfoDelete(dynamic obj)
        {
            try
            {
                int ID = Convert.ToInt32(obj.ID);
                int RT = s_DAL.OutsideUserInfosDelete(ID);
                if (RT > 0)
                {
                    Log.Info(obj.key.ToString(), "用户管理", "短信组用户删除成功！");
                }
                return RT;
            }
            catch (Exception ex)
            {
                Log.Error("UsersInfoController", ex.ToString());
                return -1;
            }
        }

        /// <summary>
        /// 移除短信组用户信息
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public int OutsideUserInfoUpdate(dynamic obj)
        {
            try
            {

                U_OutsideUserInfos model = new U_OutsideUserInfos();
                model.ID = Convert.ToInt32(obj.ID);
                model.CreateTime = DateTime.Now;
                model.IsDisable = false;
                model.UserName = obj.UserName;
                model.UserPhone = obj.UserPhone;
                model.IsFireSMS = obj.IsFireSMS;
                model.IsSafeSMS = obj.IsSafeSMS;
                model.IsResponSMS = obj.IsResponSMS;
                model.PositionID = obj.PositionID;
                model.PositionName = obj.PositionName;
                model.DepName = obj.DepName;
                model.Sort = obj.Sort;
                int RT = s_DAL.OutsideUserInfosUpdate(model);
                if (RT > 0)
                {
                    Log.Info(obj.key.ToString(), "用户管理", "短信组用户更新成功！");
                }
                return RT;
            }
            catch (Exception ex)
            {
                Log.Error("UsersInfoController", ex.ToString());
                return -1;
            }
        }

        /// <summary>
        /// 查看短信组单条信息
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public dynamic OutsideUserInfoDetail(dynamic obj)
        {
            try
            {
                int id = Convert.ToInt32(obj.ID);
                return s_DAL.OutsideUserInfosDetail(id);
            }
            catch (Exception ex)
            {
                Log.Error("UsersInfoController", ex.ToString());
                return null;
            }
        }


        /// <summary>
        /// 获取短信用户
        /// </summary>
        /// <returns>电话簿列表</returns>
        [System.Web.Http.HttpPost]
        public dynamic GetUserPhoneList(dynamic obj)
        {
            try
            {
                List<View_SmsPhone> result = new List<View_SmsPhone>();
                result = f_bll.GetLeader();
                int selectType = obj == null || Convert.ToInt32(obj.SelectType) == 0 ? 1 : Convert.ToInt32(obj.SelectType);
                List<U_OutsideUserInfos> outList = s_DAL.OutsideUserInfosSelect(selectType);
                for (int i = 0; i < outList.Count; i++)
                {
                    result.Add(new View_SmsPhone()
                    {
                        Phone = outList[i].UserPhone,
                        UserName = outList[i].UserName,
                        UserID = 1000000 + outList[i].ID
                    });
                }
                return result;
            }
            catch (Exception ex)
            {
                Log.Error("UsersInfoController", ex.ToString());
                return new List<View_SmsPhone>();
            }
        }

        #endregion
    }
}